// https://www.lintcode.com/problem/diameter-of-binary-tree/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: a root of binary tree
     * @return: return a integer
     */
    public int diameterOfBinaryTree(TreeNode root) {
        // write your code here
        /*
        根节点为root的二叉树的直径
        max(root-left的直径, \
        - root->right的直径, \
        - root->left的最大深度 + root->right的最大深度)
        重点：此路径不一定会通过树根
        */
        if (root == null) {
            return 0;
        }
        int ld = diameterOfBinaryTree(root.left);
        int rd = diameterOfBinaryTree(root.right);
        return Math.max(Math.max(ld, rd), depth(root.left) + depth(root.right));
    }
    
    protected int depth(TreeNode node) {
        if (node == null) {
            return 0;
        }
        return Math.max(depth(node.left), depth(node.right)) + 1;
    }
}